import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {InspectionService} from "../inspection.service";
import {ConfirmationService} from "primeng/primeng";
import {FormBuilder, Validators} from "@angular/forms";

@Component({
  selector: 'app-add-or-update-inspection',
  templateUrl: './add-or-update-inspection.component.html',
  styleUrls: ['./add-or-update-inspection.component.scss']
})
export class AddOrUpdateInspectionComponent implements OnInit {
  @Output() closeAddMask = new EventEmitter();
  @Output() addDev = new EventEmitter(); //添加巡检周期
  @Output() updateDev = new EventEmitter(); //修改巡检周期
  @Input() currentInspection;
  @Input() state;
  formBuilder: FormBuilder = new FormBuilder();
  addCycle;
  display :boolean = false;
  title = '添加';
  width;
  windowSize;
  inspectionCycles =[
    {label:'天', value:'天'},
    {label:'周', value:'周'},
    {label:'月', value:'月'},
    {label:'季度', value:'季度'},
    ];
  submitAddInspection = {
    "name":"",
    "cycle":this.inspectionCycles[0]['label']
  };//提交
  constructor(
    private inspectionService: InspectionService,
    private confirmationService: ConfirmationService
  ) { }

  ngOnInit() {
    this.windowSize = window.innerWidth;
    if(this.windowSize<1024){
      this.width = this.windowSize*0.4;
    }else{
      this.width = this.windowSize*0.6;
    }
    this.display = true;
    this.currentInspection = this.inspectionService.deepClone(this.currentInspection);
    if(this.state === 'update'){
      this.title = '修改'
    }
    this.addCycle = this.formBuilder.group({
      inspectionName: ['', Validators.required],
      inspectiondepartment:'',
    });
  }
  addDevice(bool){
    this.inspectionService.addInspection(this.submitAddInspection).subscribe(()=>{
      this.addDev.emit(bool);
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }
  updateDevice(bool){
     this.inspectionService.updateInspection(this.currentInspection).subscribe(()=>{
       this.updateDev.emit(this.currentInspection);
       this.closeAddMask.emit(bool)
     })
  }
  closeInspectionMask(bool){
    this.closeAddMask.emit(bool)
  }
  formSubmit(bool){
    if(this.state ==='add'){
      this.addDevice(bool)
    }else{
      this.updateDevice(bool)
    }
  }
}
